package utils

import (
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"gitee.com/zxs-micro/zxs-micro-common/grpc/protos/common"
	"github.com/golang/protobuf/proto"
	"github.com/pkg/errors"
	"sync"
)

var s256 = sha256.New()
var hashlock sync.Mutex

func MarshalOrPanic(pb proto.Message) []byte {
	data, err := proto.Marshal(pb)
	if err != nil {
		panic(err)
	}
	return data
}

func UnmarshalOrPanic(bs []byte, msg proto.Message) {
	err := proto.Unmarshal(bs, msg)
	if err != nil {
		panic(err)
	}
}

func Sha256Encode(before string) string {
	hashlock.Lock()
	defer hashlock.Unlock()
	s256.Reset()
	s256.Write([]byte(before))
	after := s256.Sum(nil)
	return base64.StdEncoding.EncodeToString(after)
}

func GenerateCommonHearder(cert string) (*common.SignatureHeader, error) {
	var h = new(common.SignatureHeader)
	h.Creator = []byte(cert)
	n, err := getRandomNonce()
	if err != nil {
		return nil, err
	}
	h.Nonce = n
	return h, nil
}

func getRandomNonce() ([]byte, error) {
	key := make([]byte, 24)

	_, err := rand.Read(key)
	if err != nil {
		return nil, errors.Wrap(err, "error getting random bytes")
	}
	return key, nil
}
